﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.Text;
using log4net;

namespace FileDistributor.Notification
{
    public class MailSender
    {
        private readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private bool _mailSent;

        public void SendMail(string fromMail, string toMail, string subject, string message)
        {
            SendMail(fromMail, toMail, subject, message, null);
        }

        public void SendMail(string fromMail, string toMail, string subject, string message, string attachmentPath)
        {
            var smtpClient = new SmtpClient();
            var from = new MailAddress(fromMail);
            var to = new MailAddress(toMail);
            Attachment attachment = null;
            
            var mailMessage = new MailMessage(from, to);
            mailMessage.Body = message;
            mailMessage.BodyEncoding =  Encoding.UTF8;
            mailMessage.Subject = subject;
            mailMessage.SubjectEncoding = Encoding.UTF8;

            if(!string.IsNullOrEmpty(attachmentPath))
            {
                attachment = new Attachment(attachmentPath);
                mailMessage.Attachments.Add(attachment);
            }
            
            smtpClient.SendCompleted += SendCompletedHandler;

            // userState is a token/unique identifier for this operation and can be any object but in this case it should be a string.
            var userState = subject;
            smtpClient.SendAsync(mailMessage, userState);

            if (_mailSent == false)
            {
                smtpClient.SendAsyncCancel();
            }

            mailMessage.Dispose();

            if (attachment != null)
            {
                attachment.Dispose();
            }
        }

        private void SendCompletedHandler(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
            var token = (string) e.UserState;

            if (e.Cancelled)
            {
                _logger.Debug("Mail canceled, token: " + token);
            }
            if (e.Error != null)
            {
                _logger.Error("Failed to send mail, token: " + token, e.Error);
            } 
            else
            {
                _logger.Debug("Mail sent.");
            }
            _mailSent = true;
        }
    
    }
}
